<template>
  <view class="user-edit-page">
    <!-- 页面头部 -->
    <view class="page-header">
      <text class="page-title">编辑资料</text>
      <text class="page-subtitle">完善您的个人信息</text>
    </view>

    <!-- 表单内容 -->
    <scroll-view scroll-y class="form-container">
      <form @submit="handleSubmit" @reset="handleReset">
        <!-- 个人信息卡片 -->
        <view class="form-card">
          <view class="card-header">
            <text class="card-title">个人信息</text>
          </view>

          <view class="form-item">
            <text class="label">用户姓名</text>
            <input
              class="input"
              type="text"
              v-model="formData.nickname"
              placeholder="请输入用户姓名"
              maxlength="20"
            />
          </view>

          <view class="form-item">
            <text class="label">手机号码</text>
            <input
              class="input"
              type="number"
              v-model="formData.phonenumber"
              placeholder="请输入手机号码"
              maxlength="11"
            />
          </view>

          <view class="form-item">
            <text class="label">邮箱地址</text>
            <input
              class="input"
              type="text"
              v-model="formData.email"
              placeholder="请输入邮箱地址"
              maxlength="50"
            />
          </view>
        </view>

        <!-- 工作信息卡片 -->
        <view class="form-card">
          <view class="card-header">
            <text class="card-title">工作信息</text>
          </view>

          <view class="form-item">
            <text class="label">班次</text>
            <picker
              mode="selector"
              :range="workShiftOptions"
              range-key="label"
              :value="workShiftIndex"
              @change="handleWorkShiftChange"
            >
              <view class="picker-input">
                <text class="picker-text">{{
                  workShiftText || "请选择班次"
                }}</text>
                <text class="picker-arrow">→</text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">班别</text>
            <picker
              mode="selector"
              :range="workClassOptions"
              range-key="label"
              :value="workClassIndex"
              @change="handleWorkClassChange"
            >
              <view class="picker-input">
                <text class="picker-text">{{
                  workClassText || "请选择班别"
                }}</text>
                <text class="picker-arrow">→</text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">所属工序</text>
            <picker
              mode="selector"
              :range="processOptions"
              range-key="processName"
              :value="processIndex"
              @change="handleProcessChange"
            >
              <view class="picker-input">
                <text class="picker-text">{{
                  processText || "请选择工序"
                }}</text>
                <text class="picker-arrow">→</text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">所属机组</text>
            <picker
              mode="selector"
              :range="prodCenterOptions"
              range-key="prodCenter"
              :value="prodCenterIndex"
              @change="handleProdCenterChange"
              :disabled="!formData.processNo"
            >
              <view class="picker-input">
                <text class="picker-text">{{
                  prodCenterText ||
                  (formData.processNo ? "请选择机组" : "请先选择工序")
                }}</text>
                <text class="picker-arrow">→</text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">所属仓库</text>
            <picker
              mode="selector"
              :range="warehouseOptions"
              range-key="label"
              :value="warehouseIndex"
              @change="handleWarehouseChange"
            >
              <view class="picker-input">
                <text class="picker-text">{{
                  warehouseText || "请选择仓库"
                }}</text>
                <text class="picker-arrow">→</text>
              </view>
            </picker>
          </view>
        </view>

        <!-- 提交按钮 -->
        <view class="submit-section">
          <button
            class="submit-btn"
            form-type="submit"
            :disabled="isSubmitting"
          >
            {{ isSubmitting ? "保存中..." : "保存修改" }}
          </button>
          <button class="cancel-btn" form-type="reset" :disabled="isSubmitting">
            重置
          </button>
        </view>
      </form>
    </scroll-view>

    <!-- 加载提示 -->
    <view class="loading-mask" v-if="isLoading">
      <view class="loading-content">
        <text class="loading-text">加载中...</text>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState, mapActions } from "vuex";
import {
  getWorkShiftDict,
  getWorkClassDict,
  getWarehouseDict,
} from "@/api/md/dict";
import { getProcessList } from "@/api/md/process";
import { UserService, SystemService } from "@/api/system/user";

export default {
  name: "UserEdit",
  data() {
    return {
      // 表单数据
      formData: {
        nickname: "",
        phonenumber: "",
        email: "",
        workShift: "",
        workClass: "",
        processNo: "",
        processName: "",
        prodCenterNo: "",
        prodCenter: "",
        wmCode: "",
        wmName: "",
      },
      // 下拉选项
      workShiftOptions: [],
      workClassOptions: [],
      processOptions: [],
      prodCenterOptions: [],
      warehouseOptions: [],
      // 选中索引
      workShiftIndex: -1,
      workClassIndex: -1,
      processIndex: -1,
      prodCenterIndex: -1,
      warehouseIndex: -1,
      // 状态
      isLoading: false,
      isSubmitting: false,
    };
  },
  computed: {
    ...mapState("user", ["userInfo", "workInformation"]),

    // 显示文本
    workShiftText() {
      const item = this.workShiftOptions[this.workShiftIndex];
      return item ? item.label : "";
    },
    workClassText() {
      const item = this.workClassOptions[this.workClassIndex];
      return item ? item.label : "";
    },
    processText() {
      const item = this.processOptions[this.processIndex];
      return item ? item.processName : "";
    },
    prodCenterText() {
      const item = this.prodCenterOptions[this.prodCenterIndex];
      return item ? item.prodCenter : "";
    },
    warehouseText() {
      const item = this.warehouseOptions[this.warehouseIndex];
      return item ? item.label : "";
    },
  },
  async onLoad(options) {
    await this.initializePageData(options);
  },
  methods: {
    ...mapActions("user", ["GetInfo"]),

    // 页面初始化 - 获取最新数据并初始化表单
    async initializePageData(options) {
      try {
        this.isLoading = true;

        // 1. 确保用户基础数据已加载
        if (!this.$store.state.user.id) {
          await this.loadUserData();
        }

        // 2. 获取最新用户配置（强制刷新缓存）
        await this.fetchLatestUserConfig();

        // 3. 初始化表单数据（优先使用userConfig）
        this.initFormDataFromStore();

        // 4. 加载下拉选项
        await this.loadOptions();

        // 5. 如果已有工序数据，确保机组选项正确加载并匹配
        if (this.formData.processNo && this.formData.prodCenterNo) {
          // 重新加载机组选项确保数据最新
          await this.loadProdCenterOptions();

          // 重新匹配机组索引
          this.prodCenterIndex = this.prodCenterOptions.findIndex(
            (option) =>
              option.prodCenterNo === this.formData.prodCenterNo ||
              option.value === this.formData.prodCenterNo
          );
          if (
            this.prodCenterIndex === -1 &&
            this.prodCenterOptions.length > 0
          ) {
            this.prodCenterIndex = 0;
          }
        }

        // 6. 初始化选中状态
        this.initSelectedIndex();
      } catch (error) {
        uni.showToast({
          title: "初始化失败",
          icon: "error",
        });
      } finally {
        this.isLoading = false;
      }
    },

    // 获取最新用户配置（强制刷新缓存）
    async fetchLatestUserConfig() {
      try {
        const userId = this.$store.state.user.id;
        if (!userId) {
          return;
        }

        // 强制刷新缓存获取最新配置
        await this.$store.dispatch("user/getUserConfigWithCache", {
          userId,
          forceRefresh: true,
        });
      } catch (error) {
        // 静默处理错误
      }
    },

    // 从Store初始化表单数据（优先使用userConfig）
    initFormDataFromStore() {
      try {
        const userData = this.$store.state.user;
        const userConfig = userData.userConfig || {};
        const workInfo = userData.workInfo || {};

        // 优先使用userConfig中的数据，如果没有则使用workInfo
        this.formData = {
          // 个人信息 - 使用userData中的数据
          nickname: userData.nickname || userData.username || "",
          email: userData.email || "",
          phonenumber:
            userData.mobile ||
            userData.phonenumber ||
            this.formData.phonenumber ||
            "", // 优先使用store中的手机号

          // 工作信息 - 优先使用userConfig数据
          workShift:
            userConfig.workShift ||
            userConfig.work_shift ||
            workInfo.workShift ||
            workInfo.work_shift ||
            "",
          workClass:
            userConfig.workClass ||
            userConfig.work_class ||
            workInfo.workClass ||
            workInfo.work_class ||
            "",

          // 工序信息
          processNo:
            userConfig.processNo ||
            userConfig.process ||
            workInfo.processNo ||
            workInfo.process ||
            "",
          processName:
            userConfig.processName ||
            userConfig.process_name ||
            workInfo.processName ||
            workInfo.process_name ||
            "",

          // 机组信息
          prodCenterNo:
            userConfig.prodCenterNo ||
            userConfig.prodLine ||
            userConfig.prod_line ||
            workInfo.prodCenterNo ||
            workInfo.prodLine ||
            workInfo.prod_line ||
            "",
          prodCenter:
            userConfig.prodCenter ||
            userConfig.prodCenterName ||
            userConfig.prod_center_name ||
            workInfo.prodCenter ||
            workInfo.prodCenterName ||
            workInfo.prod_center_name ||
            "",

          // 仓库信息 - 支持多种字段格式
          wmCode:
            userConfig.wmCode ||
            userConfig.warehouse ||
            workInfo.wmCode ||
            workInfo.warehouse ||
            "",
          wmName:
            userConfig.wmName ||
            userConfig.warehouseName ||
            userConfig.warehouse_name ||
            workInfo.wmName ||
            workInfo.warehouseName ||
            workInfo.warehouse_name ||
            "",
        };
      } catch (error) {
        // 静默处理初始化错误
      }
    },

    // 加载用户数据
    async loadUserData() {
      try {
        this.isLoading = true;
        await this.GetInfo();
      } catch (error) {
        uni.showToast({
          title: "加载数据失败",
          icon: "none",
        });
      } finally {
        this.isLoading = false;
      }
    },

    // 从URL参数初始化表单数据（已废弃，使用initFormDataFromStore）
    initFormDataFromParams(params) {
      // 此方法已废弃，仅用于保留phonenumber参数
      if (params.phonenumber) {
        this.formData.phonenumber = params.phonenumber;
      }
    },
    // 加载下拉选项
    async loadOptions() {
      try {
        // 使用引入的方法加载所有选项
        await Promise.all([
          this.loadWorkShiftOptions(),
          this.loadWorkClassOptions(),
          this.loadProcessOptions(),
          this.loadWarehouseOptions(),
        ]);

        // 如果有工序数据，先加载对应的机组选项
        if (this.formData.processNo) {
          await this.loadProdCenterOptions();
        }

        // 初始化选中索引
        this.initSelectedIndex();
      } catch (error) {
        uni.showToast({
          title: "加载选项失败",
          icon: "none",
        });
      }
    },

    // 加载班次选项
    async loadWorkShiftOptions() {
      try {
        const res = await getWorkShiftDict();

        if (res.code === 0 && res.data) {
          this.workShiftOptions = res.data;
        } else {
          this.workShiftOptions = [];
        }
      } catch (error) {
        this.workShiftOptions = [];
      }
    },

    // 加载班别选项
    async loadWorkClassOptions() {
      try {
        const res = await getWorkClassDict();

        if (res.code === 0 && res.data) {
          this.workClassOptions = res.data.map((item) => ({
            value: item.value,
            label: item.label,
          }));
        } else {
          this.workClassOptions = [];
        }
      } catch (error) {
        this.workClassOptions = [];
      }
    },

    // 加载工序选项
    async loadProcessOptions() {
      try {
        const res = await getProcessList();
        if (res.code === 0 && res.data) {
          this.processOptions = res.data;
        }
      } catch (error) {
        // 静默处理错误
      }
    },

    // 加载机组选项
    async loadProdCenterOptions() {
      try {
        let options = [];

        if (this.formData.processNo) {
          // 当所属工序有值时，根据工序编码获取对应的机组
          options = await SystemService.getProdCenterOptions(
            this.formData.processNo
          );
        } else {
          // 当所属工序无值时，全查机组列表数据
          options = await SystemService.getProdCenterOptions();
        }

        this.prodCenterOptions = options;
      } catch (error) {
        this.prodCenterOptions = [];
      }
    },

    // 加载仓库选项
    async loadWarehouseOptions() {
      try {
        const res = await getWarehouseDict();

        if (res.code === 0 && res.data) {
          this.warehouseOptions = res.data;
        } else {
          this.warehouseOptions = [];
        }
      } catch (error) {
        this.warehouseOptions = [];
      }
    },

    // 初始化选中索引
    initSelectedIndex() {
      // 班次索引
      this.workShiftIndex = this.workShiftOptions.findIndex(
        (item) => item.value === this.formData.workShift
      );
      if (this.workShiftIndex === -1 && this.workShiftOptions.length > 0) {
        this.workShiftIndex = 0;
      }

      // 班别索引
      this.workClassIndex = this.workClassOptions.findIndex(
        (item) => item.value === this.formData.workClass
      );
      if (this.workClassIndex === -1 && this.workClassOptions.length > 0) {
        this.workClassIndex = 0;
      }

      // 工序索引
      this.processIndex = this.processOptions.findIndex(
        (item) => item.processNo === this.formData.processNo
      );
      if (this.processIndex === -1 && this.processOptions.length > 0) {
        this.processIndex = 0;
      }

      // 机组索引
      this.prodCenterIndex = this.prodCenterOptions.findIndex(
        (item) =>
          item.prodCenterNo === this.formData.prodCenterNo ||
          item.value === this.formData.prodCenterNo
      );
      if (this.prodCenterIndex === -1 && this.prodCenterOptions.length > 0) {
        this.prodCenterIndex = 0;
      }

      // 仓库索引 - 增强匹配逻辑
      this.warehouseIndex = -1;
      if (this.formData.wmCode) {
        // 优先使用编码匹配
        this.warehouseIndex = this.warehouseOptions.findIndex(
          (item) => item.value === this.formData.wmCode
        );
      }

      // 如果编码匹配失败，尝试使用名称匹配
      if (
        this.warehouseIndex === -1 &&
        this.formData.wmName &&
        this.warehouseOptions.length > 0
      ) {
        this.warehouseIndex = this.warehouseOptions.findIndex(
          (item) =>
            item.label === this.formData.wmName ||
            item.value === this.formData.wmName
        );
      }

      // 如果仍未找到且存在仓库选项，则默认选中第一个
      if (this.warehouseIndex === -1 && this.warehouseOptions.length > 0) {
        this.warehouseIndex = 0;
      }
    },

    // 事件处理
    handleWorkShiftChange(e) {
      this.workShiftIndex = e.detail.value;
      const item = this.workShiftOptions[this.workShiftIndex];
      this.formData.workShift = item ? item.value : "";
    },

    handleWorkClassChange(e) {
      this.workClassIndex = e.detail.value;
      const item = this.workClassOptions[this.workClassIndex];
      this.formData.workClass = item ? item.value : "";
    },

    async handleProcessChange(e) {
      this.processIndex = e.detail.value;
      const item = this.processOptions[this.processIndex];

      if (item) {
        this.formData.processNo = item.processNo;
        this.formData.processName = item.processName;

        // 重置机组选择
        this.prodCenterIndex = -1;
        this.formData.prodCenterNo = "";
        this.formData.prodCenter = "";
        this.prodCenterOptions = [];

        // 加载对应机组
        await this.loadProdCenterOptions();

        // 重新匹配机组索引
        if (this.formData.prodCenterNo && this.prodCenterOptions.length > 0) {
          this.prodCenterIndex = this.prodCenterOptions.findIndex(
            (option) =>
              option.prodCenterNo === this.formData.prodCenterNo ||
              option.value === this.formData.prodCenterNo
          );
          if (this.prodCenterIndex === -1) {
            this.prodCenterIndex = 0;
          }
        }
      }
    },

    handleProdCenterChange(e) {
      this.prodCenterIndex = e.detail.value;
      const item = this.prodCenterOptions[this.prodCenterIndex];

      if (item) {
        this.formData.prodCenterNo = item.prodCenterNo;
        this.formData.prodCenter = item.prodCenter;
      }
    },

    handleWarehouseChange(e) {
      this.warehouseIndex = e.detail.value;
      const item = this.warehouseOptions[this.warehouseIndex];

      if (item) {
        this.formData.wmCode = item.value;
        this.formData.wmName = item.label;
      }
    },

    // 表单提交
    async handleSubmit(e) {
      // 表单验证
      if (!this.validateForm()) {
        return;
      }

      try {
        this.isSubmitting = true;

        // 更新用户基本信息
        await this.updateUserInfo();

        // 更新用户配置信息
        await this.updateUserConfig();

        uni.showToast({
          title: "保存成功",
          icon: "success",
        });

        // 返回上一页并刷新
        setTimeout(() => {
          // 使用navigateBack并传递参数通知上一页刷新
          const pages = getCurrentPages();
          if (pages.length >= 2) {
            const prevPage = pages[pages.length - 2];
            if (prevPage && prevPage.$vm) {
              // 调用上一页的刷新方法
              prevPage.$vm.handleRefresh && prevPage.$vm.handleRefresh();
            }
          }
          uni.navigateBack();
        }, 1500);
      } catch (error) {
        uni.showToast({
          title: "保存失败，请重试",
          icon: "none",
        });
      } finally {
        this.isSubmitting = false;
      }
    },

    // 表单验证
    validateForm() {
      // 手机号验证
      if (
        this.formData.phonenumber &&
        !/^1[3-9]\d{9}$/.test(this.formData.phonenumber)
      ) {
        uni.showToast({
          title: "请输入正确的手机号码",
          icon: "none",
        });
        return false;
      }

      // 邮箱验证
      if (
        this.formData.email &&
        !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.formData.email)
      ) {
        uni.showToast({
          title: "请输入正确的邮箱地址",
          icon: "none",
        });
        return false;
      }

      return true;
    },

    // 更新用户基本信息
    async updateUserInfo() {
      // 获取当前用户信息
      const userData = this.$store.state.user;
      const userId = userData.id;

      const data = {
        id: userId,
        nickname: this.formData.nickname,
        username: userData.username,
        password: userData.password,
        email: this.formData.email,
        mobile: this.formData.phonenumber,
      };

      const res = await UserService.updateUserInfo(data);
      if (res.code !== 0) {
        throw new Error(res.msg || "更新用户信息失败");
      }
    },

    // 更新用户配置信息
    async updateUserConfig() {
      // 获取当前用户配置信息
      const userData = this.$store.state.user;
      const userConfig = userData.userConfig || {};

      // 构建配置数据对象
      const data = {
        userId: userData.id,
        wmCode: this.formData.wmCode,
        wmName: this.formData.wmName,
        workShift: this.formData.workShift,
        workClass: this.formData.workClass,
        processNo: this.formData.processNo, // 工序编码
        processName: this.formData.processName,
        prodCenterNo: this.formData.prodCenterNo, // 机组编码
        prodCenter: this.formData.prodCenter, // 机组名称
      };

      // 如果用户配置已存在ID，则传入ID进行更新；否则作为新增处理
      if (userConfig.id) {
        data.id = userConfig.id;
      }

      const res = await UserService.updateUserConfig(data);
      if (res.code !== 0) {
        throw new Error(res.msg || "更新用户配置失败");
      }
    },

    // 根据仓库编码获取仓库名称
    getWarehouseName(warehouseCode) {
      const warehouse = this.warehouseOptions.find(
        (item) => item.value === warehouseCode
      );
      return warehouse ? warehouse.label : warehouseCode;
    },

    // 显示用户配置信息（调试用，已废弃）
    showUserConfigInfo() {
      // 此方法已废弃，所有调试日志已删除
    },

    // 表单重置
    handleReset() {
      // 重置时重新从store获取最新数据
      this.initFormDataFromStore();
      this.initSelectedIndex();

      uni.showToast({
        title: "已重置",
        icon: "none",
      });
    },

    // 显示用户配置信息（调试用，已清空）
    showUserConfigInfo() {
      // 此方法已清空，保留空实现
    },
  },
};
</script>

<style lang="scss" scoped>
.user-edit-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-header {
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  padding: 40rpx 30rpx;
  color: white;

  .page-title {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 8rpx;
  }

  .page-subtitle {
    display: block;
    font-size: 28rpx;
    opacity: 0.9;
  }
}

.form-container {
  flex: 1;
  padding: 20rpx;
}

.form-card {
  background: white;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

  .card-header {
    margin-bottom: 30rpx;

    .card-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
}

.form-item {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  .label {
    width: 160rpx;
    font-size: 30rpx;
    color: #666;
    flex-shrink: 0;
  }

  .input {
    flex: 1;
    font-size: 30rpx;
    color: #333;
    padding: 0 20rpx;
    height: 60rpx;
    line-height: 60rpx;

    &:disabled {
      color: #999;
      background-color: #f5f5f5;
    }
  }

  .picker-input {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 24rpx;
    height: 72rpx;
    line-height: 72rpx;
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    border: 2rpx solid #e9ecef;
    border-radius: 12rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;

    &:hover {
      border-color: #1890ff;
      box-shadow: 0 4rpx 12rpx rgba(24, 144, 255, 0.15);
    }

    &:disabled {
      opacity: 0.6;
      background: #f5f5f5;
    }

    .picker-text {
      font-size: 30rpx;
      color: #333;
      font-weight: 500;
    }

    .picker-arrow {
      font-size: 28rpx;
      color: #999;
      transform: rotate(90deg);
      transition: transform 0.3s ease;
    }
  }
}

.submit-section {
  padding: 40rpx 30rpx;

  .submit-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
    color: white;
    border-radius: 44rpx;
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 20rpx;

    &:disabled {
      opacity: 0.6;
    }
  }

  .cancel-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    background: white;
    color: #666;
    border-radius: 44rpx;
    font-size: 32rpx;
    border: 2rpx solid #ddd;

    &:disabled {
      opacity: 0.6;
    }
  }
}

.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;

  .loading-content {
    background: white;
    padding: 40rpx 60rpx;
    border-radius: 16rpx;

    .loading-text {
      font-size: 30rpx;
      color: #333;
    }
  }
}
</style>
